# 简化的启动诊断脚本
param(
    [string]$PublishPath = "bin\Release\net6.0\publish"
)

Write-Host "=== SqlsugarService.API 启动诊断 ===" -ForegroundColor Green

# 1. 检查发布文件
Write-Host "`n1. 检查发布文件..." -ForegroundColor Yellow
$requiredFiles = @(
    "SqlsugarService.API.dll",
    "SqlsugarService.API.exe", 
    "appsettings.json"
)

foreach ($file in $requiredFiles) {
    $filePath = Join-Path $PublishPath $file
    if (Test-Path $filePath) {
        Write-Host "✅ $file 存在" -ForegroundColor Green
    } else {
        Write-Host "❌ $file 缺失" -ForegroundColor Red
    }
}

# 2. 检查.NET运行时
Write-Host "`n2. 检查.NET运行时..." -ForegroundColor Yellow
try {
    $dotnetVersion = dotnet --version
    Write-Host "✅ .NET 版本: $dotnetVersion" -ForegroundColor Green
} catch {
    Write-Host "❌ .NET 运行时未安装" -ForegroundColor Red
}

# 3. 尝试启动应用
Write-Host "`n3. 尝试启动应用..." -ForegroundColor Yellow
$originalLocation = Get-Location
try {
    Set-Location $PublishPath
    Write-Host "当前目录: $(Get-Location)" -ForegroundColor Gray
    
    # 设置环境变量
    $env:ASPNETCORE_ENVIRONMENT = 'Development'
    $env:ASPNETCORE_URLS = 'http://localhost:5000'
    
    Write-Host "启动应用程序..." -ForegroundColor Cyan
    
    # 使用Start-Process启动并捕获输出
    $psi = New-Object System.Diagnostics.ProcessStartInfo
    $psi.FileName = "dotnet"
    $psi.Arguments = "SqlsugarService.API.dll"
    $psi.UseShellExecute = $false
    $psi.RedirectStandardOutput = $true
    $psi.RedirectStandardError = $true
    $psi.CreateNoWindow = $true
    
    $process = [System.Diagnostics.Process]::Start($psi)
    
    # 等待几秒钟
    Start-Sleep -Seconds 3
    
    if (!$process.HasExited) {
        Write-Host "✅ 应用程序启动成功" -ForegroundColor Green
        
        # 测试HTTP响应
        try {
            Start-Sleep -Seconds 2
            $response = Invoke-WebRequest -Uri "http://localhost:5000/health" -TimeoutSec 5 -UseBasicParsing
            Write-Host "✅ HTTP响应正常: $($response.StatusCode)" -ForegroundColor Green
        } catch {
            Write-Host "⚠️ HTTP响应测试失败: $($_.Exception.Message)" -ForegroundColor Yellow
        }
        
        # 停止进程
        $process.Kill()
        Write-Host "测试进程已停止" -ForegroundColor Gray
        
    } else {
        Write-Host "❌ 应用程序立即退出" -ForegroundColor Red
        
        # 读取错误输出
        $stdout = $process.StandardOutput.ReadToEnd()
        $stderr = $process.StandardError.ReadToEnd()
        
        if ($stdout) {
            Write-Host "标准输出:" -ForegroundColor Gray
            Write-Host $stdout -ForegroundColor Gray
        }
        
        if ($stderr) {
            Write-Host "错误输出:" -ForegroundColor Red
            Write-Host $stderr -ForegroundColor Red
        }
    }
    
} catch {
    Write-Host "❌ 启动失败: $($_.Exception.Message)" -ForegroundColor Red
} finally {
    Set-Location $originalLocation
}

# 4. 检查端口占用
Write-Host "`n4. 检查端口占用..." -ForegroundColor Yellow
try {
    $portCheck = netstat -an | Select-String ":5000"
    if ($portCheck) {
        Write-Host "⚠️ 端口5000可能被占用:" -ForegroundColor Yellow
        Write-Host $portCheck -ForegroundColor Gray
    } else {
        Write-Host "✅ 端口5000可用" -ForegroundColor Green
    }
} catch {
    Write-Host "无法检查端口状态" -ForegroundColor Yellow
}

# 5. 提供解决建议
Write-Host "`n=== 解决建议 ===" -ForegroundColor Magenta
Write-Host "• 检查数据库连接是否正常" -ForegroundColor White
Write-Host "• 确保防火墙允许端口5000" -ForegroundColor White
Write-Host "• 查看Windows事件日志中的应用程序错误" -ForegroundColor White
Write-Host "• 尝试在命令行中直接运行: dotnet SqlsugarService.API.dll" -ForegroundColor White
Write-Host "• 启用详细日志: 设置环境变量 ASPNETCORE_ENVIRONMENT=Development" -ForegroundColor White

Write-Host "`n=== 手动测试命令 ===" -ForegroundColor Magenta
Write-Host "cd $PublishPath" -ForegroundColor Cyan
Write-Host "`$env:ASPNETCORE_ENVIRONMENT='Development'" -ForegroundColor Cyan
Write-Host "`$env:ASPNETCORE_URLS='http://localhost:5000'" -ForegroundColor Cyan
Write-Host "dotnet SqlsugarService.API.dll" -ForegroundColor Cyan

Write-Host "`n诊断完成!" -ForegroundColor Green
